<?php

class BidService extends DataBaseService{

	private $_customerId;
	private $_bidType;
	private $_bidTypeArray=array();
	private $_bidSourceType;
	private $_amount;
	private $_bidExpiredModel;
	private $_customerBidInfoModel;
	private $_bidPackPrice;
	private $_bonus;
	private $_paymentMethod;
	private $_productId;
	private $_note;
	private $_buyBidPackIds = '1,2,3,4,5';//=  '1,7,91,165,218';
	private $_earnedBidLogId;
	private $_auctionId = 0;
	private $_newBidType;
	private $_db;
	
	public function init(){
		$this->_bidExpiredModel = new BidExpired();
		$this->_customerBidInfoModel = new CustomerBidInfo();
		$this->_log 	= Yii::app()->fileLog;
		$this->_db = Yii::app()->db;
		$this->log()->setNamespace('bid');
		$this->log()->addDir(get_class($this));
		$this->log()
		->addDir(date('Y'))
		->addDir(date('m'))
		->addDir(date('d'))
		->addDir(date('H'));
		$this->log()->setFile(get_class($this));
		$this->log()->addLog('Bid Start','START');
		return $this;
	}
	
	protected function log(){
		return $this->_log;
	}
	
	public function setCustomerId($customerId){
		$this->_customerId = $customerId;
		return $this;
	}
	
	public function getCustomerId(){
		return $this->_customerId;
	}
	
	public function setAuctionId($auctionId){
		$this->_auctionId = $auctionId;
		return $this;
	}
	
	public function getAuctionId(){
		return $this->_auctionId;
	}
	
	public function setBidType($bidType){
		$this->_bidType = $bidType;
		return $this;
	}
	
	public function getBidType(){
		return $this->_bidType;
	} 
	
	public function setBidSourceType($bidSourceType){
		$this->_bidSourceType = $bidSourceType;
		return $this;
	}
	
	public function getBidSourceType(){
		return $this->_bidSourceType;
	}
	
	public function setAmount($amount){
		$this->_amount = $amount;
		return $this;
	}
	
	public function getAmount(){
		return $this->_amount;
	}
	
	public function setBonus($bonus){
		$this->_bonus = $bonus;
		return $this;
	}
	
	public function getBouns(){
		return $this->_bonus;
	}
	
	public function setBidPackPrice($bidPackPrice){
		$this->_bidPackPrice = $bidPackPrice;
		return $this;
	}
	
	public function getBidPackPrice(){
		return $this->_bidPackPrice;
	}
	
	public function setPaymentMethod($paymentMethod){
		$this->_paymentMethod = $paymentMethod;
		return $this;
	}
	
	public function getPaymentMethod(){
		return $this->_paymentMethod;
	}
	
	public function setProductId($productId){
		$this->_productId = $productId;
		return $this;
	}
	
	public function getProductId(){
		return $this->_productId;
	}
	
	public function setNote($note){
		$this->_note = $note;
		return $this;
	}
	
	public function getNote(){
		return $this->_note;
	}
	
	public function setBuyBidPackIds($buyBidPackIds){
		$this->_buyBidPackIds = $buyBidPackIds;
		return $this;
	}
	
	public function getBuyBidPackIds(){
		return $this->_buyBidPackIds;
	}
	
	public function setBidTypeArray($bidTypeArray){
		$this->_bidTypeArray = $bidTypeArray;
		return $this;
	}
	
	public function getBidTypeArray(){
		return $this->_bidTypeArray;
	}
	
	public function getNewBidType(){
		return $this->_newBidType;
	}
	
	public function addBid(){
		try{
			if($this->_bidType == 1){
				$expiredTime = time()+ConstService::REAL_BIDS_EXPIRED_TIME*3600;
				$amount = $this->_amount;
			}
			if($this->_bidType == 2){
				$expiredTime = time()+ConstService::VOUCHER_BIDS_EXPIRED_TIME*3600;
				$amount = $this->_bonus;
			}
			$this->_bidExpiredModel->customer_id = $this->_customerId;
			$this->_bidExpiredModel->bid_source_type = $this->_bidSourceType;
			$this->_bidExpiredModel->bid_type = $this->_bidType;
			$this->_bidExpiredModel->amount = $amount;
			$this->_bidExpiredModel->value = $this->_bidPackPrice;
			$this->_bidExpiredModel->expired_time = $expiredTime;
			$this->_bidExpiredModel->save();
			
			$params = array(
					':cid'		=>	$this->_customerId,
					':btype'	=>  $this->_bidType,
			);
			
			$this->_customerBidInfoModel->updateAll(array('last_use_date'=>time()),'customer_id = :cid and bid_type = :btype',$params);
			$update = $this->_customerBidInfoModel->updateCounters(array('bid_num'=>$amount,'max_bid_num'=>$amount),'customer_id = :cid and bid_type = :btype',$params);
			if(!$update){
				$time = time();
				$this->_customerBidInfoModel->customer_id = $this->_customerId;
				$this->_customerBidInfoModel->bid_type = $this->_bidType;
				$this->_customerBidInfoModel->bid_num = $amount;
				$this->_customerBidInfoModel->use_num = 0;
				$this->_customerBidInfoModel->max_bid_num = $amount;
				$this->_customerBidInfoModel->last_use_date = $time;
				$this->_customerBidInfoModel->is_open = 0;	
				$num  = $this->_customerBidInfoModel->save();
				return true;
			}
		}catch(Exception $e){
			var_dump($e->getMessage());
// 			die;
			$this->log()->addLog($e->getMessage(),'ERROR');
			return false;
		}
	}
	
	public function lessBid(){
		$this->getAllBidType();			
		try{
			$lessBidSql = "
				UPDATE 
					`customer_bid_info` 
				SET 
					`customer_bid_info`.`bid_num` = `customer_bid_info`.`bid_num`-".$this->_amount.",
					`customer_bid_info`.`use_num` = `customer_bid_info`.`use_num`+".$this->_amount.",
					`customer_bid_info`.`last_use_date` = ".time()." 
				WHERE
					`customer_bid_info`.`customer_id` = ".$this->_customerId." 
				AND
					`customer_bid_info`.`bid_type` = ".$this->_bidType." 
				AND
					`customer_bid_info`.`bid_num` >= ".$this->_amount;
			$update = $this->_db->createCommand($lessBidSql)->execute();
			$this->_newBidType = $this->_bidType;
			if(!$update){
				foreach ($this->_bidTypeArray as $bidtype){
					if($bidtype != $this->_bidType){
						$lessBidSql = "
							UPDATE
								`customer_bid_info`
							SET
								`customer_bid_info`.`bid_num` = `customer_bid_info`.`bid_num`-".$this->_amount.",
								`customer_bid_info`.`use_num` = `customer_bid_info`.`use_num`+".$this->_amount.",
								`customer_bid_info`.`last_use_date` = ".time()."
							WHERE
								`customer_bid_info`.`customer_id` = ".$this->_customerId."
							AND
								`customer_bid_info`.`bid_type` = ".$bidtype."
							AND
								`customer_bid_info`.`bid_num` >= ".$this->_amount;
						$update = $this->_db->createCommand($lessBidSql)->execute();
						if($update){
							$updateCustomerSql = "
								UPDATE
									`customer`
								SET
									`customer`.`bid_type` = ".$bidtype."
								WHERE
									`customer`.`id` = ".$this->_customerId."
							";
							$this->_db->createCommand($updateCustomerSql)->execute();
							$this->_newBidType = $bidtype;
							break;
						}
					}
				}
			}
			
			if($update){
				$bidexpiredUpdateSql = "
					UPDATE
						`bid_expired`
					SET
						`bid_expired`.`amount` = `bid_expired`.`amount`-1 
					WHERE
						`bid_expired`.`customer_id` = ".$this->_customerId."
					AND	
						`bid_expired`.`bid_type`	= ".$this->_bidType."
					AND
						`bid_expired`.`expired_time`> ".time()."
					AND
						`bid_expired`.`amount` 		>= ".$this->_amount."
				";
				$this->_db->createCommand($bidexpiredUpdateSql)->execute();
// 				if($params[':btype'] == 1){
// 					$useNum = $this->getCustomerUseBids();
// 					if($useNum % 10 == 0){
// 						$halobidservice = new HaloBidService();
// 						$halobidservice->setCustomerId($this->_customerId)->customerBidInfo()->addHaloBid();
// 						$this->log()->addLog('Customer : '.$this->_customerId.' Add Halo Bid 1 Count In '.time());
// 					}
// 				}
				return true;
			}
		}catch(Exception $e){
// 			var_dump($e->getMessage());
// 			die;
// 			$errorMessage = json_encode('Error message : '.$e->getMessage());
// 			$logtime = time();
// 			$this->_db->createCommand("insert into cronjob_log(cronjob_name,log_info,created,diff_time)values('LessBid_{$logtime}',$errorMessage,{$logtime},0)")->query();
// 			$this->log()->addLog($e->getMessage(),'ERROR');
			return false;
		}
		
	}
	
	public function addEarnedBidLog($parentId=0){
		try{
			$earnedBidLog = new EarnedBidLog();
			$earnedBidLog->customer_id = $this->_customerId;
			$earnedBidLog->amount = $this->_amount;
			$earnedBidLog->value = $this->_bidPackPrice;
			$earnedBidLog->bid_source_type = $this->_bidSourceType;
			$earnedBidLog->bid_type = $this->_bidType;
			$earnedBidLog->created = time();
			$earnedBidLog->note = $this->_note;
			$earnedBidLog->bid_pack_id = $this->_productId;
			$earnedBidLog->payment_method = $this->_paymentMethod;
			$earnedBidLog->promo_bids = $this->_bonus;
			$earnedBidLog->parent_id = $parentId;
			$earnedBidLog->save(false);
			/*
			if($parentId!=0){
				$this->_amount = $this->_bonus;
			}
			*/
			return $this->_earnedBidLogId = $earnedBidLog->id;
		}catch(Exception $e){
// 			var_dump($e->getMessage());
// 			die;
			$errorMessage = json_encode('Error message : '.$e->getMessage());
			$logtime = time();
			$this->_db->createCommand("insert into cronjob_log(cronjob_name,log_info,created,diff_time)values('AddEarnedBidLog_{$logtime}',$errorMessage,{$logtime},0)")->query();
// 			$this->log()->addLog($e->getMessage(),'ERROR');
		}
		
	}
	
	public function addBidHistory(){
		try{
			$tablename = Method::getBidHistoryUserTableName($this->customer_id);
			$bidhistory = new BidHistory($tablename);
			$bidHistory->customer_id = $this->_customerId;
			$bidHistory->created = time();
			$bidHistory->bid_source_type = $this->_bidSourceType;
			$bidHistory->amount = $this->_amount;
			$bidHistory->value = $this->_bidPackPrice;
			$bidHistory->bid_type = $this->_bidType;
			$bidHistory->earned_bid_log_id = $this->_earnedBidLogId;
			$bidHistory->notes = $this->_note;
			$bidHistory->enable = 1;
			$bidHistory->auction_id = $this->_auctionId;
			$bidHistory->save();
		}catch(Exception $e){
// 			var_dump($e->getMessage());
// 			die;
			$errorMessage = json_encode('Error message : '.$e->getMessage());
			$logtime = time();
			$this->_db->createCommand("insert into cronjob_log(cronjob_name,log_info,created,diff_time)values('AddBidHistory_{$logtime}',$errorMessage,{$logtime},0)")->query();
// 			$this->log()->addLog($e->getMessage(),'ERROR');
		}
	}
	
	public function getBidPackInfo(){
		$model = Products::model()->findAll('id in ('.$this->_buyBidPackIds.')');
		$typearray = array(0=>'mini',1=>'small',2=>'large',3=>'premium',4=>'ultimate');
		$i = 0;
		foreach($model as $bidmodel){
			$bidtypearray[$bidmodel->id] = $typearray[$i];
			$biddirectly[$bidmodel->id] = array(
				'bid' => $bidmodel->bids,
				'price' => $bidmodel->value_price,
			);
			$i++;
		}
		$buyBidPackInfo = array(
			'bidtypearray'	 => $bidtypearray,
			'biddirectly'	 => $biddirectly			
		);
		return $buyBidPackInfo;
	}
	
	public function getCustomerBids(){
		if(empty($this->_customerId)){
			$customerId = Yii::app()->user->id;
		}else{
			$customerId = $this->_customerId;
		}
		$customerBid['bid_1'] = $customerBid['bid_2'] = $customerBid['bid_3'] = 0;
		if(!empty($customerId)){
			$model = CustomerBidInfo::model()->findAll('customer_id = '.$customerId);
			if(!empty($model)){
				$bidnum = 0;
				foreach($model as $cbids){
					if($cbids->bid_type==1){
						Yii::app()->session['bid_1'] = !empty($cbids->bid_num)?$cbids->bid_num:0;
						$customerBid['bid_1'] = !empty($cbids->bid_num)?$cbids->bid_num:0;
					}
					if($cbids->bid_type==2){
						Yii::app()->session['bid_2'] = !empty($cbids->bid_num)?$cbids->bid_num:0;
						$customerBid['bid_2'] = !empty($cbids->bid_num)?$cbids->bid_num:0;
					}
					if($cbids->bid_type==3){
						Yii::app()->session['bid_3'] = !empty($cbids->bid_num)?$cbids->bid_num:0;
						$customerBid['bid_3'] = !empty($cbids->bid_num)?$cbids->bid_num:0;
					}
					$bidnum += $cbids->bid_num;
				}
				Yii::app()->session['bidsnum'] = $bidnum;
				$customerBidType = Customer::model()->findByPk($customerId);
				$customerBid['bidsnum'] = $bidnum;
				$customerBid['bid_type'] = !empty($customerBidType)?$customerBidType->bid_type:1;
				return $customerBid;
			}
		}
	}
	
	public function getCustomerUseBids(){
		$useNum = 0;
		if(!empty($this->_customerId)){
			$params = array(
					':cid'		=>	$this->_customerId,
					':btype'	=>  $this->_bidType,
			);
			$useNum = CustomerBidInfo::model()->find('customer_id = :cid and bid_type = :btype',$params)->use_num;
		}
		return $useNum;
	}
	
	public function getAllBidType(){
		if(empty($this->_bidTypeArray)){
			$type = BidType::model()->findAll('bid_type_id != 3');
			foreach ($type as $key=>$val){
				$this->_bidTypeArray[$val->bid_type_id] = $val->bid_type_id;
			}
		}
		return $this;
	}

}